(function($) {
	// --------------------------------------
	YM.namespace('YM.ui');
	YM.namespace('YM.page.goodlist');
	// --------------------------------------
	YM.ui.bindGoodSelectorEvents = function(elm) {
		elm.each(function() {
			var element = $(this);
			element.find('.topitems span.more').click(function() {
				var btn = $(this), listElm = btn.parent();
				if (listElm.hasClass('topitems-min')) {
					listElm.removeClass('topitems-min');
					btn.html('收起');
				} else {
					listElm.addClass('topitems-min');
					btn.html('更多');
				}
			});
			element.find('.selector-more span').click(function() {
				if ($(this).text()=='更多') {
					element.find('.selector-items dl.hidden').slideDown();
					$(this).find('em').html('收起').addClass('collapse');
				} else {
					element.find('.selector-items dl.hidden').slideUp();
					$(this).find('em').html('更多').removeClass('collapse');
				}
			});
			element.find('.custom-price .txt-input').bindYMUI('InputLimit', { limitType:'integer' });
			element.find('.custom-price .btn-common').click(function() {
				var begin = $(this).siblings('.price-begin');
				var end = $(this).siblings('.price-end');
				if (begin.val().trim()=='') {
					YM.page.alert('请输入最低价格', function() { begin.focus(); });
					return false;
				}
				if (end.val().trim()=='') {
					YM.page.alert('请输入最高价格', function() { end.focus(); });
					return false;
				}
				document.location.href = $(this).attr('data-url').format(begin.val().trim(), end.val().trim());
				return false;
			});
			element.find('.custom-item b').click(function() {
				$(this).parent().hide();
				$(this).parent().prev().show();
			});
		});
	};
	YM.ui.bindAreaSelectorEvents = function(elm) {
		elm.bind('initSelector', function() {
			var element = $(this), elementId = element.attr('id');
			var areasElm = element.find('dl.sel-areas a'), areaHidden = element.find('input.hdsel-area'), areaTitle = element.find('.sel-title'), _selAreaId = areaHidden.val();
			areasElm.click(function() {
				var areaId = $(this).attr('areaId');
				YM.page.goodlist.updateAreaCookie(areaId);
				if (elementId=='areaSelector') {
					return true;
				}
				areasElm.removeClass('on');
				$(this).addClass('on');
				areaHidden.val(areaId);
				areaTitle.html($(this).text());
				element.mouseleave();
				YM.page.goodlist.checkGoodYear(elementId.split('_')[1], areaId, function(d) {
					var itemElm = element.closest('li');
					if (d.years.length > 0) {
						YM.page.goodlist.showGoodYears(itemElm, d.years);
					} else {
						element.parent().siblings('.sel-year p').html('');
						element.parent().siblings('.sel-year').hide();
					}
					if (d.flag==1) {
						element.siblings('.result').html('有货');
						element.parent().siblings('.sel-btn').find('.btn-big em').html('确定');
					} else {
						element.siblings('.result').html('无货');
						element.parent().siblings('.sel-btn').find('.btn-big em').html('到货通知');
					}
					element.parent().siblings('.sel-btn').find('a.btn-big').removeClass('disabled');
				});
				$('#areaSelector').trigger('updateSelector', areaId);
				return false;
			});
			if (_selAreaId!='') {
				areasElm.each(function() {
					if ($(this).attr('areaId')==_selAreaId) {
						$(this).addClass('on');
						areaTitle.html($(this).text());
					}
				});
			} else {
				if (elementId=='areaSelector' && YM.cookie.get('area-selector-viewed')!=1) {
					element.after(YM.page.goodlist.tmpls.addressTips);
					element.next().find('a.close').click(function() {
						$(this).parent().parent().fadeOut();
						YM.cookie.set('area-selector-viewed', 1, 0);
						return false;
					});
				}
			}
			element.bindYMUI('ElementHover', { hoverClass:'goods-areaselector-hover' });
		});
		elm.bind('updateSelector', function(el, areaId) {
			var element = $(this);
			element.find('input.hdsel-area').val(areaId);
			element.find('dl.sel-areas a.on').removeClass('on');
			element.find('dl.sel-areas a').each(function() {
				if ($(this).attr('areaId')==areaId) {
					$(this).addClass('on');
					element.find('.sel-title').html($(this).text());
				}
			});
			$('.goods-areaselector-tips').remove();
		});
		elm.trigger('initSelector');
	};
	YM.ui.bindGoodsListEvents = function(elm) {
		elm.each(function() {
			var element = $(this);
			element.find('ul.piclist>li').each(function(idx) {
				if ((idx+1)%5==0) $(this).addClass('col5');
				if ($.browser.isIE6) {
					$(this).bindYMUI('ElementHover', { hoverClass:'hover' });
				}
			});
			element.find('ul>li').each(function() {
				var itemElm = $(this);
				itemElm.find('.txt-prodcount').val(1).attr('id', 'amount_'+ itemElm.attr('data-goodsId'));
				if (itemElm.parent().hasClass('prodlist')) {
					itemElm.find('.txt-prodcount').bindYMUI('InputLimit', {limitType:'integer'});
					itemElm.find('.btn-down').click(function() {
						var val = parseInt($(this).next().val() || 1);
						if (val>1) $(this).next().val(val-1);
						return false;
					});
					itemElm.find('.btn-up').click(function() {
						var val = parseInt($(this).prev().val() || 0);
						$(this).prev().val(val+1);
						return false;
					});
				}
				itemElm.bind('showStockNotice', function() {
					YM.login.pop(function() {
						YM.page.goodlist.showStockNotice(itemElm.attr('data-goodsId'));
					});
				});
				if (itemElm.hasClass('soldout')) {
					itemElm.find('.btn-add2cart em').html('到货通知');
				}
				itemElm.find('.btn-add2cart').click(function() {
					if (itemElm.hasClass('soldout')) {
						itemElm.trigger('showStockNotice');
					} else {
						YM.page.goodlist.checkGoodStatus(itemElm);
					}
					return false;
				});
				if (!itemElm.hasClass('soldout') && itemElm.find('.promo-icon ins.zhe').size()>0) {
					var minprice = itemElm.find('.minprice strong').text(), maxprice = itemElm.find('.maxprice del').text().replace('¥','').replace('￥','');
					if (minprice>0 && maxprice>0) {
						var discount = (minprice * 10 / maxprice).toFixed(1);
						if (discount != '10.0')	{
							itemElm.find('.promo-icon ins.zhe').html('<em>'+ discount +'<\/em>折').removeClass('zhe');
						}
					}
				}
				if ($.browser.msie && $.browser.version<8) {
					itemElm.hover(function() {
						$(this).css('z-index', 50);
					}, function() {
						$(this).css('z-index', 0);						
					});
				}
			});
		});
	};
	YM.ui.bindGoodsViewedEvents = function(elm) {
		elm.find('li').each(function() {
			$(this).find('.btn-buy').click(function() {
				return false;
			});
		});
	};
	// --------------------------------------
	YM.page.goodlist.tmpls = {
		'addressTips': '<div class="goods-areaselector-tips"><p>请选择您的收货城市</p><p><a href="#" class="close">我知道了</a></p></div>', 
		'stockNotice': 	[
			'<div class="p20 f14"><form class="stock-notice">',
				'<p class="mb20">请选择适合您的货到提醒方式，我们将在商品到货后及时给您通知到货通知只发送一次</p>',
				'<p class="mb10"><label><input type="checkbox" name="subscribeType" value="SUBSCRIPTION_TYPE_MESSAGE" checked /> 站内信</label></p>',
				'<p class="mb10"><label><input type="checkbox" name="subscribeType" value="SUBSCRIPTION_TYPE_EMAIL" /> 邮件：</label> <input name="email" type="text" class="txt-input" /></p>',
				'<p class="mb10"><input type="hidden" name="goodsId" value="{0}" /><a class="btn-subscribe" href="#">提醒我</a><span class="error"></span></p>',
			'</form></div>'
		].join(''),
		'goodSelector': '<div class="goodselector"><a href="#" class="close" title="关闭">关闭</a></div>',
		'goodSelectorYear': '<div class="sel-year clearfix" style="display:none;"><label>年份：</label><p></p></div>',
		'yearItem': '<span amount="{amount}" goodsId="{goodsId}"{yearCss}>{year}</span>',
		'goodSelectorArea': '<div class="sel-area clearfix"><label>送至：</label><span class="result"></span></div>',
		'goodSelectorBtn': '<div class="sel-btn clearfix"><a href="#" class="btn-big disabled"><em>确定</em></a></div>'
	};
	YM.page.goodlist.updateAreaCookie = function(areaId) {
		YM.cookie.set('single_goods_area_name', areaId, 365, true);
		YM.cookie.set('search-stock-area', areaId, 365, true);
	};
	// --------------------------------------
	YM.page.goodlist.init = function() {
		// GoodSelector筛选器事件处理
		$('#goodSelector').bindYMUI('bindGoodSelectorEvents');
		// GoodNavigator导航条浮动处理
		if (!$.browser.isIE6) {
			$('#goodNavigator').bindYMUI('floatTopNav', { child:'a.returntop' });
		}
		// AreaSelector地址选择器初始化
		$('#areaSelector').bindYMUI('bindAreaSelectorEvents');
		// GoodsList商品列表事件处理
		$('#goodsList').bindYMUI('bindGoodsListEvents');
		// 浏览过的商品列表事件处理
		$('.mod-prodlist-c3').bindYMUI('bindGoodsViewedEvents');
	};
	YM.page.goodlist.checkGoodStatus = function(element) {
		if (element.find('.goodselector').size()>0) {
			element.find('.goodselector').show();
			return false;
		}
		var areaId =  $('#areaSelector input.hdsel-area').val() || '';
		if (areaId=='') {
			YM.page.goodlist.showGoodSelector(element);
		} else {
			this.checkGoodYear(element.attr('data-goodsId'), areaId, function(d) {
				if (d.flag==1) {
					if (d.years.length > 1) {
						YM.page.goodlist.showGoodSelector(element, d.years);
					} else if (d.years.length == 1) {
						YM.page.goodlist.addToCart(element, d.years[0].goodsId);
					} else {
						YM.page.goodlist.addToCart(element);
					}
				} else {
					element.addClass('soldout');
					element.find('.btn-add2cart em').html('到货通知');
					element.trigger('showStockNotice');
				}
			});
		}
	};
	// 检查库存和年份
	YM.page.goodlist.checkGoodYear = function(goodsId, areaId, callback) {
		YM.dataproxy.ajax({
			url: YM.login.servicePath +'stock/queryGoodsStock.jspa', 
			data: {
				'goodsId': goodsId,
				'areaId': areaId,
				'_': new Date().getTime()
			},
			dataType: 'json',
			success: function(d) {
				if (d.years) {
					d.years = [].concat(d.years);
					d.years.remove(0, 'goodsId');
				} else {
					d.years = [];
				}
				if (d.flag!=1) d.years = [];
				callback(d);
			},
			error: function(d) {
				callback({flag:0, years:[]});				
			}
		});
	};
	YM.page.goodlist.showGoodSelector = function(element, years) {
		element.append(YM.page.goodlist.tmpls.goodSelector);
		var goodselectorElm = element.find('.goodselector');
		goodselectorElm.append(YM.page.goodlist.tmpls.goodSelectorArea);
		goodselectorElm.append(YM.page.goodlist.tmpls.goodSelectorYear);
		goodselectorElm.append(YM.page.goodlist.tmpls.goodSelectorBtn);
		var areaselectorElm = $('#areaSelector').clone().attr('id', 'areaSelector_'+ element.attr('data-goodsId'));
		goodselectorElm.find('.sel-area label').after(areaselectorElm);			
		goodselectorElm.find('a.close').click(function() {
			goodselectorElm.fadeOut();
			return false;
		});
		goodselectorElm.find('a.btn-big').click(function() {
			if ($(this).hasClass('disabled')) return false;
			if ($(this).text()=='到货通知') {
				element.trigger('showStockNotice');
			} else {
				YM.page.goodlist.addToCart(element);
			}
			return false;
		});
		areaselectorElm.bindYMUI('bindAreaSelectorEvents');
		if (years) {
			goodselectorElm.find('.sel-area .result').html('有货');
			YM.page.goodlist.showGoodYears(element, years);
		}
	};
	YM.page.goodlist.showGoodYears = function(element, years) {
		var goodselectorElm = element.find('.goodselector');
		var yearHtml = [];
		yearHtml.push(YM.page.goodlist.tmpls.yearItem.substitute({amount:0,goodsId:0,year:'不限',yearCss:' class="on"'}));
		for (var i=0; i<years.length; i++) {
			yearHtml.push(YM.page.goodlist.tmpls.yearItem.substitute(years[i]));
		}
		goodselectorElm.find('.sel-year p').html(yearHtml.join(''));
		goodselectorElm.find('.sel-year p span').click(function() {
			$(this).siblings('.on').removeClass('on');
			$(this).addClass('on');
			goodselectorElm.find('.btn-big').removeClass('disabled');
			return false;
		});
		goodselectorElm.find('.sel-year').show();
		if (goodselectorElm.find('.sel-year p span.on').size()>0) {
			goodselectorElm.find('a.btn-big').removeClass('disabled');
		} else {
			goodselectorElm.find('a.btn-big').addClass('disabled');
		}
	};
	// 加入购物车
	YM.page.goodlist.addToCart = function(element, goodsYearId) {
		var goodsId = element.attr('data-goodsId');
		var goodselectorElm = element.find('.goodselector');
		if (goodselectorElm.size()>0) {
			goodselectorElm.hide();
			goodsYearId = goodselectorElm.find('.sel-year span.on').attr('goodsId')||0;
			YM.page.header.cart.addGood(goodsId, 'amount_'+goodsId, goodsYearId);
		} else {
			YM.page.header.cart.addGood(goodsId, 'amount_'+goodsId, goodsYearId||'');
		}	
	};
	// 到货通知
	YM.page.goodlist.showStockNotice = function(goodId) {
		var winhtml = this.tmpls.stockNotice.format(goodId);
		YM.page.dialog({ title:'到货通知', content:winhtml, width:500, height:200, callback:function() {
			$('.stock-notice a.btn-subscribe').click(function() {
				var frm = $('form.stock-notice');
				if (frm.find('input:checked').size()==0) {
					$(this).next().html('请先选择提醒方式').show().bindYMUI('HideByTimer', {animate:'fade'});
				} else if (frm.find('input[name=subscribeType]:eq(1)').attr('checked') && frm.find('input[name=email]').val().trim()=='') {					
					$(this).next().html('请输入邮件地址').show().bindYMUI('HideByTimer', {animate:'fade'});
					frm.find('input[name=email]').focus();
				} else {
					YM.dataproxy.ajax({ url:YM.login.servicePath +'notify/goodsArrivalNotify.jspa', data:frm.serialize(), dataType:'json', type:'post', success:function(data) {
						// data: {"flag":1,"msg":"","success":true}
						if (data.success) {
							YM.page.showSuccess('到货提醒已设置成功');
						} else {
							YM.page.showError(data.msg);
						}
					}});
				}
				return false;
			});		
		}});
	};
	YM.page.goodlist.initBeforeReady = function() {
		if ($('#goodSelector .selector-items dl.hidden').size()==0) {
			$('#goodSelector .selector-more').remove();
		}
		$('#goodSelector .topitems').each(function() {
			$(this).find('a:last').addClass('last');
			if ($(this).height()>40 && $(this).find('.more').size()==0) {
				$(this).addClass('topitems-min');
				$(this).prepend('<span class="more">更多</span>');
				if ($(this).find('.on').size()>0) {
					if ($(this).find('.on').offset().top - 20 > $(this).offset().top) {
						$(this).removeClass('topitems-min');
						$(this).find('span.more').html('收起');
					}
				}
			}
		});
		$('#goodSelector .custom-price').parent().addClass('items-price');
	};
	// --------------------------------------
	$(document).ready(function() {
		YM.page.goodlist.init();
	});
	YM.page.goodlist.initBeforeReady();
	// --------------------------------------
})(jQuery);